import SparkMD5 from "spark-md5";
self.onmessage = async (e) => {
  if ((e.data.type = "upload")) {
    const chunks = await createChunks(e.data.data, 1000); //拿到分片
    const hash = await fileHash(chunks);
    self.postMessage(hash);
  }
};
//计算hash值
const fileHash = (chunks) => {
  return new Promise((resolve, reject) => {
    const spark = new SparkMD5();
    function _read(i) {
      if (i >= chunks.length) {
        resolve(spark.end());
        return;
      }
      const blob = chunks[i];
      const reader = new FileReader();
      reader.onload = (e) => {
        const bytes = e.target.result;
        spark.append(bytes);
        _read(i + 1);
      };

      reader.readAsArrayBuffer(blob);
    }
    _read(0);
  });
};
//分片函数
const createChunks = (file, chunkSize) => {
  const result = [];
  for (let i = 0; i < file.size; i += chunkSize) {
    result.push(file.slice(i, i + chunkSize));
  }
  return result;
};

